package com.wymobilearchitecture.study.thread.security;

import com.example.w_library.log.WLog;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 一个用原子类修饰,一个用 volatile 修饰,在多线程的情况做自增,然后输出最后结果
 */
public class AtomicTest {

    public AtomicTest(){

        final AtomicTask task = new AtomicTask();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    task.incrementAtomic();
                    task.incrementVolatile();
                }
            }
        };

        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        WLog.e("原子类修饰的结果: " + task.atomicInteger.get());
        WLog.e("volatile修饰的结果: " + task.volatileCount);
    }

    static class AtomicTask{
        AtomicInteger atomicInteger = new AtomicInteger();
        volatile int volatileCount = 0;

        void incrementAtomic(){
            atomicInteger.getAndIncrement();
        }

        void incrementVolatile(){
            //所得结果不足两万,volatile 在非原子操作的情况下无法保证线程安全
            // ++ 属于非原子操作,有多个步骤
            volatileCount++;
        }
    }
}
